﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using OpenFileTransfer.Util.Xml;
using OpenFileTransfer.Wpf.Models;

namespace OpenFileTransfer.Wpf.Services
{
    public class ConfigService : IConfigService
    {
        public int UdpPort { get; private set; }
        public int UdpBroadcastInterval { get; private set; }
        public WebSocketServerPara WebSocketServerInfo { get; }

        /// <summary>
        /// APP数据文件夹
        /// </summary>
        public string AppDataDirectory { get; }

        /// <summary>
        /// 本地文件夹
        /// </summary>
        public string LocalFileDirectory { get; }

        private string _configName = string.Empty;

        private readonly ILogService _logService;

        public ConfigService(ILogService logService)
        {
            _logService = logService;
            WebSocketServerInfo = new WebSocketServerPara();

            //APP数据文件夹
            var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var app = typeof(ConfigService).Namespace?.Split('.').FirstOrDefault();
            AppDataDirectory = Path.Combine(path, app ?? string.Empty);

            //本地文件夹
            var info = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
            LocalFileDirectory = Path.Combine(info.Parent?.FullName ?? string.Empty, "LocalFiles");

            //创建文件夹
            CreateDirectory(AppDataDirectory);
            CreateDirectory(LocalFileDirectory);
        }

        private void CreateDirectory(string path)
        {
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception e)
                {
                    _logService.Error($"创建文件夹{path}失败：{e.Message}.");
                }
            }
        }

        #region 加载参数

        public void LoadConfig(string configName)
        {
            _configName = configName;

            //Get Config file
            var info = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
            var xmlFilePath = Path.Combine(info.Parent?.FullName ?? string.Empty, _configName);

            //从配置文件读取数据
            var xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFilePath);
            }
            catch (Exception e)
            {
                _logService.Error($@"加载配置文件[{configName}]失败：{e.Message}.");
                return;
            }

            var root = xmlDoc.SelectSingleNode("/AppSettings");
            LoadUdpConfig(root); //加载UDP参数
            LoadWebSocketServerConfig(root); //加载WebSocketServer参数
        }

        private void LoadUdpConfig(XmlNode? root)
        {
            try
            {
                var node = root?.SelectSingleNode("UDP");
                if (XmlHelper.GetNodeAttributeInt(node, "Port", out var nodeValueInt))
                {
                    UdpPort = nodeValueInt;
                }

                if (XmlHelper.GetNodeAttributeInt(node, "BroadcastInterval", out nodeValueInt))
                {
                    UdpBroadcastInterval = nodeValueInt;
                }
            }
            catch (Exception e)
            {
                _logService.Error($@"加载UDP参数异常：{e.Message}.");
            }
        }

        private void LoadWebSocketServerConfig(XmlNode? root)
        {
            try
            {
                var node = root?.SelectSingleNode("WebSocketServer");
                if (XmlHelper.GetNodeInnerInt(node, "Port", out var nodeValueInt))
                {
                    WebSocketServerInfo.Port = nodeValueInt;
                }

                if (XmlHelper.GetNodeInnerInt(node, "HeartBeatCheckInterval", out nodeValueInt))
                {
                    WebSocketServerInfo.HeartBeatCheckInterval = nodeValueInt;
                }

                if (XmlHelper.GetNodeInnerInt(node, "HeartBeatTimeout", out nodeValueInt))
                {
                    WebSocketServerInfo.HeartBeatTimeout = nodeValueInt;
                }
            }
            catch (Exception e)
            {
                _logService.Error($@"加载WebSocketServer参数异常：{e.Message}.");
            }
        }

        #endregion
    }
}
